<?php


namespace app\controller\api;


use app\BaseController;
use app\common\OrderStatus;
use app\models\goods\GoodsCartModel;
use app\models\goods\GoodsModel;
use app\models\goods\GoodsSkuModel;
use app\models\order\OrderEvaluationModel;
use app\models\order\OrderModel;
use app\models\shop\ShopModel;
use app\services\order\OrderService;
use app\services\user\DetailIntegralService;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;

use app\models\goods\CategoryModel;
use app\models\goods\GoodsCollectModel;
use app\models\order\OrderDetailModel;
use app\models\user\UserAddressModel;

use app\models\user\UserModel;
use app\services\config\ConfigService;
use app\services\user\UserService;

use app\services\pay\PayService;
use app\strategy\pay\BalancePay;
use app\strategy\pay\WxPay;
use app\strategy\pay\AliPay;


class CeshiController extends BaseController
{

    public function ceshi(){
        $pay_amount = 19.88;
        $green_scores = 0;
        $userId = 471;
        $pay = OrderService::payType($pay_amount,$green_scores,$userId);

        return $this->success($pay);
    }

    public function getShopGoodsLists(){
        try {
            $where = [];
            $shop_id = $this->request->param('shop_id');
            $keyword = $this->request->param('keyword');
            if ($keyword) {
                $where[] = ['name|intro', 'like', '%' . $keyword . '%'];
            }
            if($shop_id){
                $where[] = ['shop_id','=',$shop_id];

                $shopinfo = Db::name('shop')->where('id',$shop_id)->field('shop_name,img,logo')->find();
            }else{
                $shop_name = ConfigService::getConfigValue('shop_name');
                $shop_img = ConfigService::getConfigValue('shop_img');
                $shop_logo = ConfigService::getConfigValue('shop_logo');

                $shopinfo = ['shop_name' => $shop_name,'img' => $shop_img,'logo' => $shop_logo];
            }

            $list = GoodsModel::where('status', 1)
                ->where($where)
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->each(function ($item){
                    $item['goods_sku'] = GoodsSkuModel::where('goods_id',$item['id'])->field('goods_id,name,sell_price,market_price')->order('sort','desc')->select();
                    return $item;
                });
            $data = ['shop' => $shopinfo,'goods' => $list];
            return $this->success($data);
        }catch (\Exception $exception){
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 取消购买
     * @return \think\response\Json
     */
    public function cancelOrder()
    {
        try {
            $id = $this->request->param('id');
            $order = OrderModel::find($id);
            if(!$order){
                throw new \Exception('订单不存在！');
            }
            if($order['order_status'] != 1){
                throw new \Exception('当前状态无法取消订单！');
            }
            if($order['type'] == 2){
                //未支付运费 退回积分
                $type = DetailIntegralService::RETURN;
                DetailIntegralService::create($this->request->userId,$type,$order['pay_amount'],$order['order_sn']);
            }
            OrderModel::where(['id' => $id, 'user_id' => $this->request->userId])->update(['order_status' => 0]);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 确认订单
     */
    public function confirmOrder3()
    {
        Db::startTrans();
        try {
            $orderSn = $this->request->param('orderSn');
            $orderSnAry = $this->request->param('orderSnAry');
            $where[] = ['is_del', '=', 0];
            $where[] = ['user_id', '=', $this->request->userId];
            if($orderSnAry){
                $where[] = ['order_sn', 'in', $orderSnAry];
            }else{
                $where[] = ['order_sn', '=', $orderSn];
            }

            $data = OrderModel::where($where)
                ->field('id,type,order_sn,pay_type,total_amount,shop_id,address_id,order_type,pay_amount,create_time,delivery_time,grade_discount,coupon_amount,freight,order_status,is_evaluation')
                ->order('id', 'desc')
                ->select()
                ->toArray();
            if (!$data) {
                throw new \Exception('订单不存在');
            }


            $address = UserAddressModel::where('user_id', $this->request->userId)->where('status',1)->find();
            $freight = 0;
            $total_amount = 0;

            foreach($data as $key => &$value){

                $freight = bcadd($freight,$value['freight'],2); //运费
                $total_amount = bcadd($total_amount,$value['total_amount'],2); //商品总价

                if(intval($value['shop_id']) == 0){
                    $value['shop_name'] = '自营';
                    $value['shop_img'] = ConfigService::getConfigValue('logo');;
                }else{
                    $shop_info = ShopModel::where('id', $value['shop_id'])->find();
                    $value['shop_name'] = $shop_info['shop_name'];
                    $value['shop_img'] = $shop_info['img'];
                }

                $value['detail'] = OrderDetailModel::where('order_sn', $value['order_sn'])
                    ->field('id,goods_sku_id,goods_name,goods_price,goods_image,num')
                    ->select()
                    ->each(function ($item) {
                        $item['goods_sku_name'] = GoodsSkuModel::where('id', $item['goods_sku_id'])->value('name');
                        return $item;
                    });
            }
            $pay_amount = bcadd($total_amount,$freight,2);

            return $this->success(['freight' => $freight,'total_amount' => $total_amount,'pay_amount' => $pay_amount,'address' => $address,'order'=> $data]);
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 余额明细
     * @return \think\response\Json
     */
    public function balanceRecord()
    {
        try {
            $userId = $this->request->userId;
            $where = [];
            $where[] = ['user_id', '=', $userId];

            $start_time = $this->request->param('start_time');
            //$end_time = $this->request->param('end_time');
            $type = $this->request->param('type','all');

            if(empty($start_time)){
                $start_time = strtotime(date('Y-m-01 00:00:00'));
                $end_time  = strtotime(date('Y-m-t 23:59:59'));

                $title = date('Y-m').'月';
                $where[] = ['create_time','between',[$start_time,$end_time]];
            }else{
                $title = $start_time;
                $start_time = strtotime($start_time);
                $end_time  = strtotime(date("Y-m-t 23:59:59", strtotime($start_time.'-01')));
            }
            $where[] = ['create_time','between',[$start_time,$end_time]];

            $total_revenue = Db::name('detailed_money')
                ->where($where)
                ->where('type','<',100)
                ->sum('amount'); //总收入
            $total_expenditure = Db::name('detailed_money')->where($where)->where('type','>',100)->sum('amount'); //总支出


            if($type != 'all'){
                if($type == 101){
                    $where[] = ['type','>',100];   //扣除
                }else{
                    $where[] = ['type','<',100];   //收入
                }
            }

            $list = Db::name('detailed_money')
                ->where($where)
                ->field('id,amount,remark,create_time,type')
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])->toArray();

            foreach ($list['data'] as &$v) {
                $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            }


            $money = UserModel::where('id', $this->request->userId)->value('money');
            return $this->success([
                'data' => $list,
                'money' => $money,
                'title' => $title,
                'total_revenue' => $total_revenue,
                'total_expenditure' => $total_expenditure,
                'user_id' => $userId
            ]);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 购物车商品下单
     */
    public function confirmOrder2()
    {
        try {
            $cartIds = $this->request->param('cart_ids');
            $goods_id = $this->request->param('goods_id');
            $goods_sku_id = $this->request->param('goods_sku_id');
            $num = $this->request->param('num');
            $userId = $this->request->userId;
            $cartIds = [53];
            $userId = 451;
            //用户默认收货地址
            $address = UserAddressModel::where('user_id', $userId)->where('status',1)->find();

            //运费
            $freight = ConfigService::getConfigValue('freight');

            if(empty($cartIds)){
                $shop_info = ['shop_name' => ConfigService::getConfigValue('shop_name'),'shop_img' => ConfigService::getConfigValue('shop_logo')];
                //直接下单
                $data = [
                    "total_amount" => 0,
                    "green_scores" => 0,
                    "address" => $address,
                    "total_freight" => $freight,
                    'data' => [],//['shop' => ['shop_name' => $shop_info['shop_name'],'shop_img' => $shop_info['shop_img']],'list' => []]
                ];

                $goods = GoodsModel::find($goods_id)->toArray();
                if (!$goods) {
                    throw new \Exception('商品不存在');
                }
                if ($goods['status'] != 1) {
                    throw new \Exception('商品已下架');
                }
                $goods_sku = GoodsSkuModel::find($goods_sku_id)->toArray();
                if (!$goods_sku) {
                    throw new \Exception('规格不存在');
                }
                $shop_id = intval($goods['shop_id']);
                if($shop_id != 0){
                    $shop_info = ShopModel::where('id', $goods['shop_id'])->find();
                }
                $data['data']['shop'] = ['shop_name' => $shop_info['shop_name'],'shop_img' => $shop_info['shop_img']];
                $data['data']['list'][] = ['goods' => $goods,'sku' => $goods_sku,'num' => $num];
                $data['total_amount'] = bcmul($goods_sku['sell_price'],$num,2);
                $data['green_scores'] = bcmul($goods['green_scores'],$num,2);

                return $this->success($data);
            }else{
                //购物车下单
                $cartGoods = GoodsCartModel::whereIn('id', $cartIds)->where('user_id', $userId)->select()->toArray();

                $shop_goods = [];

                foreach($cartGoods as $key => $value){
                    $goods = GoodsModel::find($value['goods_id'])->toArray();
                    if (!$goods) {
                        throw new \Exception('商品不存在');
                    }
                    if ($goods['status'] != 1) {
                        throw new \Exception('商品已下架');
                    }
                    $goods_sku = GoodsSkuModel::find($value['goods_sku_id'])->toArray();
                    if (!$goods_sku) {
                        throw new \Exception('规格不存在');
                    }
                    $shop_id = intval($goods['shop_id']);
                    if(!isset($shop_goods[$shop_id])){
                        if($shop_id == 0){
                            $shop_info = ['shop_name' => '自营','shop_img' => ConfigService::getConfigValue('logo')];
                        }else{
                            $shop_info = ShopModel::where('id', $value['shop_id'])->find();
                        }
                        $shop_goods[$shop_id]['shop'] = $shop_info;
                        $shop_goods[$shop_id]['list'] = [];
                    }

                    $shop_goods[$shop_id]['list'][] = ['goods' => $goods,'sku' => $goods_sku,'num' => $value['num']];
                }

                $green_scores = 0;
                $total_amount = 0;
                $total_freight = 0;
                foreach($shop_goods as $key => $value){
                    $total_freight = bcadd($freight,$total_freight,2);
                    foreach($value['list'] as $item){
                        $green_scores = bcadd($green_scores,bcmul($goods['green_scores'],$item['num'],2),2);
                        $total_amount = bcadd($total_amount,bcmul($item['sku']['sell_price'],$item['num'],2),2);
                    }

                }
                return $this->success(['data' => $shop_goods,'total_amount'=> $total_amount,'green_scores' => $green_scores,'address' => $address,'total_freight' => $total_freight]);
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function createOrder()
    {
        Db::startTrans();
        try {
            $cartIds = $this->request->param('cart_ids');
            $goods_id = $this->request->param('goods_id');
            $goods_sku_id = $this->request->param('goods_sku_id');
            $num = $this->request->param('num');
            $address_id = $this->request->param('address_id');
            $pay_type = $this->request->param('pay_type');
            $userId = $this->request->userId;
            //用户默认收货地址
            $address = UserAddressModel::where('user_id', $userId)->where('id',$address_id)->find();

            //运费
            $freight = ConfigService::getConfigValue('freight');

            if(empty($cartIds)){
                $shop_info = ['shop_name' => ConfigService::getConfigValue('shop_name'),'shop_img' => ConfigService::getConfigValue('shop_logo')];
                //直接下单
                $data = [
                    "total_amount" => 0,
                    "green_scores" => 0,
                    "address" => $address,
                    "total_freight" => $freight,
                    'data' => [],//['shop' => ['shop_name' => $shop_info['shop_name'],'shop_img' => $shop_info['shop_img']],'list' => []]
                ];

                $goods = GoodsModel::find($goods_id)->toArray();
                if (!$goods) {
                    throw new \Exception('商品不存在');
                }
                if ($goods['status'] != 1) {
                    throw new \Exception('商品已下架');
                }
                $goods_sku = GoodsSkuModel::find($goods_sku_id)->toArray();
                if (!$goods_sku) {
                    throw new \Exception('规格不存在');
                }
                $shop_id = intval($goods['shop_id']);
                if($shop_id != 0){
                    $shop_info = ShopModel::where('id', $goods['shop_id'])->find();
                }
                $data['data']['shop'] = ['shop_name' => $shop_info['shop_name'],'shop_img' => $shop_info['shop_img']];
                $data['data']['list'][] = ['goods' => $goods,'sku' => $goods_sku,'num' => $num];
                $data['total_amount'] = bcmul($goods_sku['sell_price'],$num,2);
                $data['green_scores'] = bcmul($goods['green_scores'],$num,2);

                $shop_goods = $data;
            }else{
                //购物车下单
                $cartGoods = GoodsCartModel::whereIn('id', $cartIds)->where('user_id', $userId)->select()->toArray();

                $shop_goods = [];

                foreach($cartGoods as $key => $value){
                    $goods = GoodsModel::find($value['goods_id'])->toArray();
                    if (!$goods) {
                        throw new \Exception('商品不存在');
                    }
                    if ($goods['status'] != 1) {
                        throw new \Exception('商品已下架');
                    }
                    $goods_sku = GoodsSkuModel::find($value['goods_sku_id'])->toArray();
                    if (!$goods_sku) {
                        throw new \Exception('规格不存在');
                    }
                    $shop_id = intval($goods['shop_id']);
                    if(!isset($shop_goods[$shop_id])){
                        if($shop_id == 0){
                            $shop_info = ['shop_name' => '自营','shop_img' => ConfigService::getConfigValue('logo')];
                        }else{
                            $shop_info = ShopModel::where('id', $value['shop_id'])->find();
                        }
                        $shop_goods[$shop_id]['shop'] = $shop_info;
                        $shop_goods[$shop_id]['list'] = [];
                    }

                    $shop_goods[$shop_id]['list'][] = ['goods' => $goods,'sku' => $goods_sku,'num' => $value['num']];
                }

                $green_scores = 0;
                $total_amount = 0;
                $total_freight = 0;
                foreach($shop_goods as $key => $value){
                    $total_freight = bcadd($freight,$total_freight,2);
                    foreach($value['list'] as $item){
                        $green_scores = bcadd($green_scores,bcmul($goods['green_scores'],$item['num'],2),2);
                        $total_amount = bcadd($total_amount,bcmul($item['sku']['sell_price'],$item['num'],2),2);
                    }
                }
            }

            //创建订单
            $orderSnAry = [];
            foreach($shop_goods as $key => $value){
                $orderSn = createOrderSn();
                $effective_purchase = 0;
                $order_detail = [];
                $green_scores = 0;
                $total_amount = 0;
                foreach($value['list'] as $item){
                    if($item['goods']['effective_purchase'] == 1){
                        $effective_purchase = 1;
                    }
                    $order_detail[] = [
                        'order_sn' => $orderSn,
                        'goods_id' => $item['goods']['id'],
                        'goods_name' => $item['goods']['name'],
                        'goods_sku_id' => $item['sku']['id'],
                        'goods_price' => $item['sku']['sell_price'],
                        'num' => $item['num'],
                        'goods_image' => $item['goods']['image'],
                        'create_time' => time(),
                        'green_scores' => bcmul($item['goods']['green_scores'],$item['num'],2),
                        'effective_purchase' => $effective_purchase
                    ];
                    $green_scores = bcadd($green_scores,bcmul($item['goods']['green_scores'],$item['num'],2),2);
                    $total_amount = bcadd($total_amount,bcmul($item['sku']['sell_price'],$item['num'],2),2);
                }

                $order_data = [
                    'order_sn' => $orderSn,
                    'type' => 1,
                    'coupon_id' => 1,
                    'pay_type' => $pay_type,
                    'order_type' => 2,
                    'address_id' => 0,
                    'freight' => $freight,
                    'user_id' => $userId,
                    'order_status' => 1,
                    'effective_purchase' => $effective_purchase,
                    'green_scores' => $green_scores,
                    'total_amount' => $total_amount,
                    'pay_amount' => $total_amount + $freight,
                    'shop_id' => $key,
                    'create_time' => time()
                ];
                if(!empty($address)){
                    $order_data['username'] = $address['username'];
                    $order_data['user_mobile'] = $address['user_mobile'];
                    $order_data['address_detail'] = $address['full_address'];
                    $order_data['address_id'] = $address['address_id'];
                }
                Db::name('order')->insert($order_data);
                foreach($order_detail as $detail){
                    OrderDetailModel::create($detail);
                }
                $orderSnAry[] = $orderSn;
            }
            if(empty($cartIds)){
                GoodsCartModel::destroy($cartIds);
            }
            return $this->success(['order_sn' => $orderSn,'orderSnAry'=> $orderSnAry]);
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 售后
     * @return void
     */
    public function after_sales()
    {
        try {
            $id = $this->request->param('id');
            $after_sales_type = $this->request->param('after_sales_type');
            $order = OrderModel::find($id);
            if(!$order){
                throw new \Exception('订单不存在！');
            }
            if(in_array($order['order_status'],[0,1,2])){
                throw new \Exception('当前状态无法取消订单！');
            }

            OrderModel::where(['id' => $id, 'user_id' => $this->request->userId])->update([
                'order_status' => 7,
                'after_sales_type'=> $after_sales_type,
                'after_sales_time' => time(),
                'after_sales_status' => $order['order_status']
            ]);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

}